package com.miqtech.master.wyrecorder.ui;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.miqtech.master.wyrecorder.R;
import com.miqtech.master.wyrecorder.annotations.LayoutId;
import com.miqtech.master.wyrecorder.annotations.Title;
import com.miqtech.master.wyrecorder.base.BaseAppCompatActivity;
import com.miqtech.master.wyrecorder.constants.API;
import com.miqtech.master.wyrecorder.entity.Gift;
import com.miqtech.master.wyrecorder.entity.User;
import com.miqtech.master.wyrecorder.screenrecorder.Constants;
import com.miqtech.master.wyrecorder.screenrecorder.share.ExpertMorePopupWindow;
import com.miqtech.master.wyrecorder.screenrecorder.share.ShareToFriendsUtil;
import com.miqtech.master.wyrecorder.user.UserProxy;
import com.miqtech.master.wyrecorder.utils.DeviceUtils;
import com.miqtech.master.wyrecorder.utils.DownloadImage;
import com.miqtech.master.wyrecorder.utils.L;
import com.miqtech.master.wyrecorder.utils.ToastUtils;
import com.miqtech.master.wyrecorder.utils.imageloader.AsyncImage;
import com.miqtech.master.wyrecorder.widget.CircleImageView;
import com.pgyersdk.crash.PgyCrashManager;
import com.pgyersdk.update.PgyUpdateManager;
import com.tencent.tauth.Tencent;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by arvin on 2016/10/28.
 */
@LayoutId(R.layout.activity_main)
@Title(titleId = R.string.app_name)
public class MainActivity extends BaseAppCompatActivity implements UserProxy.OnUserChangeListener {

    @BindView(R.id.img_anchor_header)
    CircleImageView imgAnchorHeader;
    @BindView(R.id.tv_anchor_name)
    TextView tvAnchorName;
    @BindView(R.id.tv_anchor_room)
    TextView tvAnchorRoom;
    @BindView(R.id.tv_anchor_fans)
    TextView tvAnchorFans;
    @BindView(R.id.tv_version)
    TextView tvVersion;
    private ShareToFriendsUtil shareToFriendsUtil;//分享
    private ExpertMorePopupWindow popwin;//分享弹框


    @Override
    protected void initViews(Bundle savedInstanceState) {
        PgyCrashManager.register(this);
        if (Constants.isStreaming) {
            Intent intent = new Intent(this, ScreenRecorderActivity.class);
            // intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            startActivity(intent);
        } else {
            hideBack();
            initAnchorInfo();
            UserProxy.addListener(this);
            getGiftList();
        }
        PgyUpdateManager.register(MainActivity.this,getString(R.string.file_provider));
    }

    private void initAnchorInfo() {
        User user = UserProxy.getUser();
        if (user != null) {
            AsyncImage.displayImageSmall(user.getIcon(), imgAnchorHeader, R.drawable.default_head);
            tvAnchorFans.setText(user.getFans() + "");
            tvAnchorName.setText(user.getNickname());
            tvAnchorRoom.setText(user.getRoomNumber());
            tvVersion.setText("V:" + DeviceUtils.getVersionName(this));

            if (user.getIsCertificate() == 1) {
                Drawable d = getResources().getDrawable(R.drawable.authentication_bak);
                d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
                tvAnchorName.setCompoundDrawables(null, null, d, null);
            } else {
                tvAnchorName.setCompoundDrawables(null, null, null, null);
            }
        }
        popwin = new ExpertMorePopupWindow(this, R.style.Dialog);
        popwin.setOnItemClick(itemOnClick);
        shareToFriendsUtil = new ShareToFriendsUtil(this, popwin);
    }

    @OnClick({R.id.ivShare, R.id.ll_start, R.id.ll_info})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ivShare:
                if (popwin != null) {
                    popwin.show();
                }
                break;
            case R.id.ll_start:
                if (inBlackList()) {
                    ToastUtils.show("由于缺少必要的系统组件，您的机型暂不支持直播", 3000);
                } else {
                    Intent intent = new Intent();
                    intent.setClass(this, SelectGameActivity.class);
                    startActivity(intent);
                    this.overridePendingTransition(R.anim.activityy_bottom_in, 0);
                }
                break;
            case R.id.ll_info:
                jumpToActivity(AnchorHomeActivity.class);
                break;
        }
    }

    @Override
    public void onBackPressed() {
        moveTaskToBack(true);
    }


    @Override
    public void onUserChange(User user) {
        if (user == null) {
            imgAnchorHeader.setImageResource(R.drawable.default_head);
            tvAnchorName.setText("");
            tvAnchorFans.setText("");
            tvAnchorRoom.setText("");
        } else {
            AsyncImage.displayImageSmall(user.getIcon(), imgAnchorHeader, R.drawable.default_head);
            tvAnchorFans.setText(user.getFans() + "");
            tvAnchorName.setText(user.getNickname());
            tvAnchorRoom.setText(user.getRoomNumber());
            tvVersion.setText("V:" + DeviceUtils.getVersionName(this));
        }
    }

    private void downLoadGiftImg(List<Gift> gifts) {
        for (Gift gift : gifts) {
            DownloadImage.getInstance().download(gift.getNoFrameIcon());
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        L.e(TAG, "hhha");
    }


    /**
     * 获取礼物列表
     */
    private void getGiftList() {
        sendHttpRequest(API.GIFT_LIST, null, false);
    }

    @Override
    public void onSuccess(JSONObject object, String method) {
        super.onSuccess(object, method);
        try {
            List<Gift> giftList = new Gson().fromJson(object.getJSONObject("object").getJSONArray("list").toString(),
                    new TypeToken<List<Gift>>() {
                    }.getType());
            Gift yuer = new Gift();
            yuer.setNoFrameIcon("uploads/imgs/live/2016/11/18/a143ea585d6041c3aa3bb64f89b16a69.png");
            giftList.add(yuer);
            downLoadGiftImg(giftList);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10103 || requestCode == 10104) {
            Tencent.onActivityResultData(requestCode, resultCode, data, shareToFriendsUtil.getQQUIListener());
            return;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (UserProxy.getUser() == null) {
            jumpToActivity(LoginActivity.class);
        }
    }

    View.OnClickListener itemOnClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            User user = UserProxy.getUser();
            if (user == null) {
                ToastUtils.show("还没有登录");
                return;
            }
            String sharetitle = "手游直播就上娱儿TV！";
            String sharecontent = "我在娱儿TV开播啦，求抱抱求围观求投食！";
//            String shareurl = API.HOST
////                    + API.LIVE_SHARE + id;
//                    + API.LIVE_SHARE + "";//原本应该传的是直播id，因为ios传的是主播id（已过审核），所以将错就错传主播id
            String shareurl = user.getShareUrl();
            String imgurl;
            imgurl = API.IMAGE_HOST + user.getIcon();

            switch (v.getId()) {
                case R.id.llSina:
                    shareToFriendsUtil.shareBySina(sharetitle, sharecontent, shareurl, imgurl);
                    break;
                case R.id.llWeChat:
                    shareToFriendsUtil.shareWyByWXFriend(sharetitle, sharecontent, shareurl, imgurl, 0);
                    break;
                case R.id.llFriend:
                    shareToFriendsUtil.shareWyByWXFriend(sharetitle, sharecontent, shareurl, imgurl, 1);
                    break;
                case R.id.llQQ:
                    shareToFriendsUtil.shareByQQ(sharetitle, sharecontent, shareurl, imgurl);
                    break;
            }
        }
    };

    private boolean inBlackList() {
        if (!TextUtils.isEmpty(DeviceUtils.getPhoneModel())) {
            String[] blacklist = getResources().getStringArray(R.array.blacklist);
            for (String black : blacklist) {
                if (black.equals(DeviceUtils.getPhoneModel())) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        UserProxy.removeListener(this);
        PgyCrashManager.unregister();
    }
}
